const UserModel = require('../models/user.model');
const { generateToken } = require('../utils/jwt');
const bcrypt = require('bcryptjs');
const { ValidationError } = require('../middleware/error');

class UserController {
  // 用户注册
  static async register(req, res, next) {
    try {
      console.log('开始处理注册请求:', { 
        username: req.body.username,
        email: req.body.email,
        hasPassword: !!req.body.password,
        hasConfirmation: !!req.body.password_confirmation,
        nickname: req.body.nickname
      });

      const { username, email, password, password_confirmation, nickname } = req.body;

      // 基本验证
      const errors = {};
      
      // 用户名验证
      if (!username) {
        errors.username = ['用户名不能为空'];
      } else if (username.length < 3 || username.length > 50) {
        errors.username = ['用户名长度必须在3-50个字符之间'];
      } else if (!/^[a-zA-Z0-9_]+$/.test(username)) {
        errors.username = ['用户名只能包含字母、数字和下划线'];
      }

      // 邮箱验证
      if (!email) {
        errors.email = ['邮箱不能为空'];
      } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        errors.email = ['请提供有效的邮箱地址'];
      }

      // 密码验证
      if (!password) {
        errors.password = ['密码不能为空'];
      } else if (password.length < 6 || password.length > 30) {
        errors.password = ['密码长度必须在6-30个字符之间'];
      } else if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(password)) {
        errors.password = ['密码必须包含至少一个大写字母、一个小写字母和一个数字'];
      }

      // 确认密码验证
      if (!password_confirmation) {
        errors.password_confirmation = ['请确认密码'];
      } else if (password !== password_confirmation) {
        errors.password_confirmation = ['两次输入的密码不匹配'];
      }

      // 昵称验证（可选）
      if (nickname && (nickname.length < 1 || nickname.length > 50)) {
        errors.nickname = ['昵称长度必须在1-50个字符之间'];
      }

      if (Object.keys(errors).length > 0) {
        console.log('验证失败:', errors);
        throw new ValidationError('注册信息验证失败', errors);
      }

      console.log('验证通过，开始创建用户');

      // 创建用户
      const user = await UserModel.create({
        username: username.trim(),
        email: email.trim().toLowerCase(),
        password,
        nickname: (nickname || username).trim()
      });

      console.log('用户创建成功，准备生成令牌:', { userId: user.id });

      if (!user || !user.id) {
        console.error('用户创建异常：返回的用户对象无效');
        throw new Error('用户创建失败');
      }

      // 生成JWT令牌
      const token = generateToken(user);

      if (!token) {
        console.error('令牌生成失败');
        throw new Error('令牌生成失败');
      }

      console.log('令牌生成成功，准备发送响应');

      const response = {
        message: '用户注册成功',
        data: {
          user: {
            id: user.id,
            username: user.username,
            email: user.email,
            nickname: user.nickname,
            created_at: user.created_at
          },
          access_token: token,
          token_type: 'Bearer',
          expires_in: parseInt(process.env.JWT_EXPIRES_IN) || 7200
        }
      };

      console.log('发送注册成功响应');
      res.status(201).json(response);
    } catch (error) {
      console.error('注册过程发生错误:', error);
      next(error);
    }
  }

  // 用户登录
  static async login(req, res, next) {
    try {
      console.log('开始处理登录请求:', { login_identifier: req.body.login_identifier, hasPassword: !!req.body.password });
      const { login_identifier, password } = req.body;

      // 基本验证
      if (!login_identifier || !password) {
        console.log('登录验证失败: 缺少登录凭证或密码');
        throw new ValidationError('登录失败', {
          login_identifier: !login_identifier ? ['请提供用户名或邮箱'] : undefined,
          password: !password ? ['请提供密码'] : undefined
        });
      }

      console.log('登录验证通过，开始查找用户:', login_identifier);
      // 查找用户
      const user = await UserModel.findByLoginIdentifier(login_identifier);
      if (!user) {
        console.log('登录失败: 用户未找到', login_identifier);
        throw new ValidationError('登录失败', {
          login_identifier: ['用户名/邮箱或密码不正确']
        });
      }

      console.log('用户找到，开始验证密码:', { userId: user.id });
      // 验证密码
      const isValidPassword = await bcrypt.compare(password, user.password_hash);
      if (!isValidPassword) {
        console.log('登录失败: 密码不正确', { userId: user.id });
        throw new ValidationError('登录失败', {
          // 为了安全，不明确指出是密码错误，而是统一提示
          login_identifier: ['用户名/邮箱或密码不正确']
        });
      }

      console.log('密码验证成功，准备生成令牌:', { userId: user.id });
      // 生成JWT令牌
      const token = generateToken(user);
      if (!token) {
        console.error('令牌生成失败', { userId: user.id });
        throw new Error('令牌生成失败');
      }

      console.log('令牌生成成功，准备发送响应:', { userId: user.id });
      res.json({
        message: '登录成功',
        data: {
          user: {
            id: user.id,
            username: user.username,
            email: user.email,
            nickname: user.nickname,
            created_at: user.created_at
          },
          access_token: token,
          token_type: 'Bearer',
          expires_in: parseInt(process.env.JWT_EXPIRES_IN) || 7200
        }
      });
    } catch (error) {
      console.error('登录过程发生错误:', error);
      next(error);
    }
  }

  // 获取当前用户信息
  static async getProfile(req, res, next) {
    try {
      const user = await UserModel.findById(req.user.id);
      res.json({
        data: user
      });
    } catch (error) {
      next(error);
    }
  }

  // 更新用户信息
  static async updateProfile(req, res, next) {
    try {
      const { nickname } = req.body;

      if (!nickname || nickname.trim().length === 0) {
        throw new ValidationError('更新失败', {
          nickname: ['昵称不能为空']
        });
      }

      const user = await UserModel.updateProfile(req.user.id, { nickname });
      res.json({
        message: '个人信息更新成功',
        data: user
      });
    } catch (error) {
      next(error);
    }
  }

  // 修改密码
  static async updatePassword(req, res, next) {
    try {
      const { current_password, new_password, new_password_confirmation } = req.body;

      // 验证新密码
      if (!new_password || new_password.length < 6) {
        throw new ValidationError('密码更新失败', {
          new_password: ['新密码至少需要6个字符']
        });
      }

      if (new_password !== new_password_confirmation) {
        throw new ValidationError('密码更新失败', {
          new_password_confirmation: ['两次输入的新密码不匹配']
        });
      }

      await UserModel.updatePassword(req.user.id, current_password, new_password);
      res.json({
        message: '密码更新成功'
      });
    } catch (error) {
      next(error);
    }
  }

  // 新增：获取用户收货地址列表
  static async getUserAddresses(req, res, next) {
    try {
      const userId = req.user.id;
      console.log(`[UserController.getUserAddresses] Fetching addresses for userId: ${userId}`);
      const addresses = await UserModel.getAddressesByUserId(userId);
      res.json({
        data: addresses
      });
    } catch (error) {
      console.error(`[UserController.getUserAddresses] Error fetching addresses for userId: ${req.user.id}:`, error);
      next(error);
    }
  }

  // 添加新收货地址
  static async addAddress(req, res, next) {
    try {
      const userId = req.user.id;
      console.log(`[UserController.addAddress] Adding new address for userId: ${userId}`);
      
      // 验证必填字段
      const requiredFields = ['recipient_name', 'phone_number', 'street_address', 'city', 'province'];
      for (const field of requiredFields) {
        if (!req.body[field]) {
          return res.status(400).json({
            message: `缺少必填字段: ${field}`
          });
        }
      }

      const newAddress = await UserModel.addAddress(userId, req.body);
      res.status(201).json({
        message: 'Address added successfully.',
        data: newAddress
      });
    } catch (error) {
      console.error(`[UserController.addAddress] Error adding address for userId: ${req.user.id}:`, error);
      next(error);
    }
  }

  // 更新指定收货地址
  static async updateAddress(req, res, next) {
    try {
      const userId = req.user.id;
      const addressId = req.params.addressId;
      console.log(`[UserController.updateAddress] Updating address ${addressId} for userId: ${userId}`);
      
      // 验证必填字段
      const requiredFields = ['recipient_name', 'phone_number', 'street_address', 'city', 'province'];
      for (const field of requiredFields) {
        if (!req.body[field]) {
          return res.status(400).json({
            message: `缺少必填字段: ${field}`
          });
        }
      }

      const updatedAddress = await UserModel.updateAddress(addressId, req.body, userId);
      res.json({
        message: '地址更新成功',
        data: updatedAddress
      });
    } catch (error) {
      console.error(`[UserController.updateAddress] Error updating address for userId: ${req.user.id}:`, error);
      next(error);
    }
  }

  // 删除指定收货地址
  static async deleteAddress(req, res, next) {
    try {
      const userId = req.user.id;
      const addressId = req.params.addressId;
      console.log(`[UserController.deleteAddress] Deleting address ${addressId} for userId: ${userId}`);

      await UserModel.deleteAddress(addressId, userId);
      res.json({
        message: '地址删除成功'
      });
    } catch (error) {
      console.error(`[UserController.deleteAddress] Error deleting address for userId: ${req.user.id}:`, error);
      next(error);
    }
  }

  // 设置默认地址
  static async setDefaultAddress(req, res, next) {
    try {
      const userId = req.user.id;
      const addressId = req.params.addressId;
      console.log(`[UserController.setDefaultAddress] Setting address ${addressId} as default for userId: ${userId}`);

      const updatedAddress = await UserModel.setDefaultAddress(addressId, userId);
      res.json({
        message: '默认地址设置成功',
        data: updatedAddress
      });
    } catch (error) {
      console.error(`[UserController.setDefaultAddress] Error setting default address for userId: ${req.user.id}:`, error);
      next(error);
    }
  }
}

module.exports = UserController; 